package com.qf.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.qf.entity.User;
import com.qf.service.CartService;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin("*")
@RestController
@RequestMapping("/cart")
public class CartController {

    private CartService cartService;

    public CartController(CartService cartService) {
        this.cartService = cartService;
    }


    @PostMapping("/addGood")
    public void addGood(Integer goodId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        Integer userId = user.getUId();
        cartService.addGood(userId, goodId);
    }

    @PostMapping("/updGood")
    public void updGood(Integer goodId, Integer num, HttpSession session) {
        User user = (User) session.getAttribute("user");
        Integer userId = user.getUId();
        cartService.updGood(userId, goodId, num);
    }

    @PostMapping("/delGood")
    public void delGood(Integer goodId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        Integer userId = user.getUId();
        cartService.delGood(userId, goodId);
    }

    @PostMapping("/syncCartData")
    public Object syncCartData(String localCartData, HttpSession session) {
        //返回到前端的数据
        Map<String, Object> respMsg = new HashMap<>();
        //"{"1001":1,"1002":3,"1003":4}"
        //判断session是否存在用户
        Object obj = session.getAttribute("user");
        if (obj == null) {
            respMsg.put("code", "1");
            respMsg.put("msg", "用户没有登陆");
            return respMsg;
        }
        User user = (User) obj;
        //处理json字符串，把本地购物车转为map对象
        Map<Integer, Integer> localDataMap = (Map<Integer, Integer>) JSON.parse(localCartData);
        Map<Object, Object> afterSyncCart = cartService.syncCart(localDataMap, user.getUId());
        return afterSyncCart;
    }


}
